package com.pactera.madp.cp.service.sync.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.pactera.madp.cp.api.entity.crm.WorkCustTagInfoEntity;
import com.pactera.madp.cp.api.entity.sync.SyncCustTagInfoEntity;
import com.pactera.madp.cp.common.constant.Constants;
import com.pactera.madp.cp.common.util.RedisUtil;
import com.pactera.madp.cp.context.SyncStateContext;
import com.pactera.madp.cp.mapper.sync.SyncCustTagInfoMapper;
import com.pactera.madp.cp.service.WorkCustTagInfoService;
import com.pactera.madp.cp.service.sync.CrmCustTagSyncBusinessService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@AllArgsConstructor
public class CrmCustTagSyncBusinessServiceImpl implements CrmCustTagSyncBusinessService {

    private final RedisTemplate redisTemplate;
    private final WorkCustTagInfoService workCustTagInfoService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean syncBusiness() {
        String nowDate = DateUtil.format(new Date(), Constants.DATE_FORMAT);

        // 执行同步业务
        String lockKey = RedisUtil.buildKey(Constants.SYNC_TAG_BUSINESS_LOCK, nowDate);
        try {
            // 获取同步业务的锁
            boolean isLocked = RedisUtil.getLock(lockKey, "1", Constants.EXPIRE_TIME, TimeUnit.SECONDS);
            if (!isLocked) {
                SyncStateContext.get().setSaveLog(false);
                return false;
            }
            log.info("CRM标签业务同步获取锁成功");

            // 获取临时数据
            List<SyncCustTagInfoEntity> syncList = (List<SyncCustTagInfoEntity>) SyncStateContext.get().getTempData()[3];
            if (syncList.isEmpty()) {
                return false;
            }

            // crm标签业务数据列表
            List<WorkCustTagInfoEntity> workList = new ArrayList<>();

            WorkCustTagInfoEntity prototype = new WorkCustTagInfoEntity();
            syncList.forEach(st -> {
                WorkCustTagInfoEntity wt = prototype.clone();
                BeanUtil.copyProperties(st, wt);
                workList.add(wt);
            });
            // 清空列表
            syncList.clear();

            if (workList.isEmpty()) {
                return false;
            }

            // 保存当前同步数据到业务表
            workCustTagInfoService.batchSaveAll(workList);
            // 清空列表
            workList.clear();

            log.info("已同步CRM标签业务数据量：{}", SyncStateContext.get().getTempData()[2]);
        } finally {
            redisTemplate.delete(lockKey);
            log.info("CRM标签业务同步释放锁成功");
        }
        return true;
    }

}
